#include "ExpirationNICModule.h"
#include "MainWindow.h"
#include "ui_ExpirationNIC.h"

extern QSqlDatabase enjoylifedb;
extern QSqlRelationalTableModel *expNIC_model;
extern QTableView *expNIC_view;

QString filterDomain;

ExpirationNICModule::ExpirationNICModule(QWidget *parent) :
    QMainWindow(parent)
{
    domain_toolbar = new CustomModulesToolbar(this);
    UpdateDomainsDateToolBar();
    UpdateDomainstListToolBar();
    addToolBar(domain_toolbar);
    
    setWindowTitle("Moódulo Vencimientos NIC");
    setWindowFlags(Qt::WindowCloseButtonHint);
    setWindowIcon(QIcon("://Icons/calendario-32x32.png"));

    expNIC_model = new QSqlRelationalTableModel(this,enjoylifedb);
    expNIC_model->setTable("dominio");
    expNIC_model->setEditStrategy(QSqlRelationalTableModel::OnFieldChange);

    SelectExpiratedDomains();

    expNIC_model->setHeaderData(1,Qt::Horizontal,"Razón Social");
    expNIC_model->setHeaderData(2,Qt::Horizontal,"Dominio Asociado");
    expNIC_model->setHeaderData(3,Qt::Horizontal,"Primario?");
    expNIC_model->setHeaderData(4,Qt::Horizontal,"Fecha Alta NIC");
    expNIC_model->setHeaderData(5,Qt::Horizontal,"Fecha Vto. NIC");

    expNIC_view = new QTableView(this);
    expNIC_view->setModel(expNIC_model);
    expNIC_view->hideColumn(0);
    expNIC_view->setSortingEnabled(true);
    expNIC_view->sortByColumn(1,Qt::SortOrder());
    expNIC_view->setAlternatingRowColors(true);
    expNIC_view->setGridStyle(Qt::SolidLine);
    expNIC_view->setWordWrap(true);
    expNIC_view->horizontalHeader()->setStretchLastSection(true);
    expNIC_view->setEditTriggers(QAbstractItemView::NoEditTriggers);
    expNIC_view->setColumnWidth(1, 400);
    expNIC_view->setColumnWidth(2, 350);
    expNIC_view->setColumnWidth(3, 60);
    expNIC_view->setColumnWidth(4, 240);
    expNIC_view->setColumnWidth(5, 240);
    setCentralWidget(expNIC_view);

    // Doble click sobre un cliente abre la edición.
    connect(expNIC_view,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(UpdateDomainsDateBtn()));
}

/*
 *
 */
void ExpirationNICModule::SelectExpiratedDomains()
{
    QDate date;
    QDate expDate;
    int dia1, dia2;
    int mes1, mes2;
    int anio1, anio2;
    dia1 = date.currentDate().day();
    mes1 = date.currentDate().month();
    anio1 = date.currentDate().year();
    date.setDate(anio1,mes1,dia1);
    dia2 = date.currentDate().addDays(16).day();
    if (dia2 < dia1) {
        mes2 = date.addMonths(1).month();
        if (mes2 < mes1) {
            anio2 =  date.addYears(1).year();
            expDate.setDate(anio2, mes2, dia2);
        }
        else
            expDate.setDate(anio1, mes2, dia2);
    }
    else
        expDate.setDate(anio1, mes1, dia2);

    QString format = "yyyy-MM-dd";
    QString fechaLimite = expDate.toString(format);

    filterDomain = "fecha_vencimiento_nic <= '" + fechaLimite + "'";
    expNIC_model->setTable("dominio");
    expNIC_model->setFilter(filterDomain);
    enjoylifedb.transaction();
    if (!expNIC_model->select()) {
        QMessageBox::critical(this,"Error!", "No se pudieron recuperar los registros, intentelo manualmente.");
        enjoylifedb.rollback();
        return;
    }
    enjoylifedb.commit();
}

void ExpirationNICModule::UpdateDomainsDateToolBar()
{
    update_domainsDate = new QAction("Administrar Fecha Dominio/s",this);
    update_domainsDate->setIcon(QIcon("://Icons/BarraHerramientas/administrar48.png"));
    update_domainsDate->setIconText("Administrar Fecha Dominio/s");
    update_domainsDate->setToolTip("Administra Fechas de Vencimiento de un Dominio");
    connect(update_domainsDate,SIGNAL(triggered()),this,SLOT(UpdateDomainsDateBtn()));

    domain_toolbar->addAction(update_domainsDate);
}

void ExpirationNICModule::UpdateDomainstListToolBar()
{
    update_domainstDateList = new QAction("Actualizar Lista",this);
    update_domainstDateList->setIcon(QIcon("://Icons/BarraHerramientas/actualizar48.png"));
    update_domainstDateList->setIconText("Actualizar Lista");
    update_domainstDateList->setToolTip("Actualiza la Lista Dominios Proximos a vencer o ya vencidos");
    connect(update_domainstDateList,SIGNAL(triggered()),this,SLOT(UpdateDomainsDateListBtn()));

    domain_toolbar->addAction(update_domainstDateList);
}

void ExpirationNICModule::UpdateDomainsDateBtn()
{
    // Se controla para el caso que no existan clientes cargados.
    if (expNIC_model->rowCount() == 0) {
        QMessageBox::information(this,"Información!","No hay Dominios disponibles.");
        return;
    }

    int selection = -1;
    if (!(expNIC_view->currentIndex().row() == -1)) {
        selection = expNIC_view->currentIndex().row();
    }
    if (!(selection == -1)) {
        enjoylifedb.transaction();

        ExpirationNIC *expirationForm = new ExpirationNIC();
        expirationForm->GetClientDomainsInfo(expNIC_model->index(selection,1).data().toString());
        expirationForm->show();

        enjoylifedb.commit();
    } else {
        QMessageBox::warning(this, tr("Vencimientos NIC"),
                             tr("La operación no se puede concretar."
                                "\nNingún Dominio ha sido seleccionado."));
    }
    SelectExpiratedDomains();
    CorrectViewOfModel();
}

void ExpirationNICModule::CorrectViewOfModel()
{
    expNIC_model->setHeaderData(1,Qt::Horizontal,"Razón Social");
    expNIC_model->setHeaderData(2,Qt::Horizontal,"Dominio Asociado");
    expNIC_model->setHeaderData(3,Qt::Horizontal,"Primario?");
    expNIC_model->setHeaderData(4,Qt::Horizontal,"Fecha Alta NIC");
    expNIC_model->setHeaderData(5,Qt::Horizontal,"Fecha Vto. NIC");

    expNIC_view->setModel(expNIC_model);
    expNIC_view->hideColumn(0);
    expNIC_view->setSortingEnabled(true);
    expNIC_view->sortByColumn(1,Qt::SortOrder());
    expNIC_view->setAlternatingRowColors(true);
    expNIC_view->setGridStyle(Qt::SolidLine);
    expNIC_view->setWordWrap(true);
    expNIC_view->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

void ExpirationNICModule::UpdateDomainsDateListBtn()
{
    SelectExpiratedDomains();
    CorrectViewOfModel();
}
